//
//  SystemMessageDB.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/22.
//  Copyright © 2017年 Imon. All rights reserved.
//
import UIKit
import FMDB
import JMessage

final class SystemMessageDB: NSObject {
    
    static private var share: SystemMessageDB?
    
    var queue: FMDatabaseQueue?
    
    override init() {
        super.init()
        createDB()
    }
    
    static func getShareInstance() -> SystemMessageDB? {
        if share != nil {
            return share!
        } else if !JMSGUser.myInfo().username.isEmpty {
            share = SystemMessageDB()
            return share!
        } else {
            return nil
        }
    }
    
    static func logoutInstance() {
        share = nil
    }
    
    private func createDB() {
        let user = JMSGUser.myInfo()
        if user.username.isEmpty {
            return
        }
        let dir = user.username + user.appKey!
        
        var path = "\(NSHomeDirectory())/Documents/\(dir)"
        
        if createPath(path) {
            path = path + "/SystemMessage.db"
            queue = FMDatabaseQueue(path: path)
            
            let sql = "create table IF NOT EXISTS SystemMessage(id integer primary key autoincrement, message text, has_read integer, orderId integer, role text, received_time text)"
            queue?.inDatabase { (db) in
                db?.executeUpdate(sql, withArgumentsIn: nil)
            }
        }
    }
    
    func dropTable() {
        if queue == nil {
            createDB()
        }
        let sql = "drop table if exists SystemMessage"
        queue?.inDatabase { (db) in
            db?.executeUpdate(sql, withArgumentsIn: nil)
        }
    }
    
    func insertData(_ message: SystemMessage) {
        if queue == nil {
            createDB()
        }
        
        let sql = "insert into SystemMessage(message, has_read, orderId, role, received_time) values ('\(message.message)', \(message.has_read), \(message.orderId), '\(message.role)', '\(message.received_time)')"
        
        queue?.inDatabase{ (db) in
            db?.executeUpdate(sql, withArgumentsIn: nil)
        }
    }
    
    func delete(_ message: SystemMessage) {
        if queue == nil {
            createDB()
        }
        let delSql = "delete from SystemMessage where id = \(message.id)"
        queue?.inDatabase { (db) in
            db?.executeUpdate(delSql, withArgumentsIn: nil)
        }
    }
    
    func update(_ message: SystemMessage) {
        if queue == nil {
            createDB()
        }
        let updSql = "update SystemMessage set has_read = 1 where id = \(message.id)"
        queue?.inDatabase { (db) in
            db?.executeUpdate(updSql, withArgumentsIn: nil)
        }
    }
    
    func quaryData() -> [SystemMessage] {
        if queue == nil {
            createDB()
        }
        var messages: [SystemMessage] = []
        let sql = "select * from SystemMessage order by id desc"
        queue?.inDatabase { (db) in
            let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
            while (resultSet?.next())! {
                let message = SystemMessage(id: Int((resultSet?.int(forColumn: "id"))!), message: (resultSet?.string(forColumn: "message"))!, has_read: Int((resultSet?.int(forColumn: "has_read"))!), orderId: Int((resultSet?.int(forColumn: "orderId"))!), role: (resultSet?.string(forColumn: "role"))!, received_time: (resultSet?.string(forColumn: "received_time"))!)
                messages.append(message)
            }
        }
        return messages
    }
    
    func unreadCount() -> Int {
        if queue == nil {
            createDB()
        }
        var count: Int = 0
        let sql = "select count(has_read) as count from SystemMessage where has_read = 0"
        queue?.inDatabase { (db) in
            let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
            if (resultSet?.next())! {
                count = Int((resultSet?.int(forColumn: "count"))!)
            }
        }
        return count
    }
    // MARK: - private func
    private func createPath(_ path: String) -> Bool {
        var isDir: ObjCBool = ObjCBool(false)
        
        if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue {
            return true
        } else {
            try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            return true
        }
    }
}
